package com.mall.order.mq.order;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class DelayOrderProducerReminder {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init () {
        producer = new DefaultMQProducer("send_message");

        producer.setNamesrvAddr("127.0.0.1:9876");

        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
            log.info(e.getErrorMessage());
        }

    }


    /**
     * 延迟消息取消订单
     * @param orderId
     * @return
     * @throws InterruptedException
     * @throws RemotingException
     * @throws MQClientException
     * @throws MQBrokerException
     */
    public boolean sendMessage (String orderId,String topic,int delayTimeLevel)  {

        //创建延迟消息
        Message message = new Message(topic,orderId.getBytes(StandardCharsets.UTF_8));
        message.setDelayTimeLevel(delayTimeLevel);

        SendResult send = null;
        try {
            send = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (send == null || SendStatus.SEND_OK.equals(send.getSendStatus())) {
            return false;
        }
        return true;
    }
}
